// 单线程web server
pub fn learn_single_web() {
  listen_tcp().unwrap();
}

// 监听tcp连接
use std::{
  fmt::Error, fs, io::{self, BufRead, BufReader, Write}, net::{TcpListener, TcpStream}
};

fn listen_tcp() -> Result<(), io::Error> {
  let listener = TcpListener::bind("localhost:7878")?;
  for stream in listener.incoming() {
    match stream {
      Ok(stream) => handle_connection1(stream),
      Err(e) => {
        println!("{}", e);
      }
    }
  }

  Ok(())
}

// 读取请求
fn handle_connection0(mut stream: TcpStream) {
  let buf_reader = BufReader::new(&mut stream);
  let http_request: Vec<_> = buf_reader
    .lines()
    .map(|result| result.unwrap_or(String::new()))
    .take_while(|line| !line.is_empty())
    .collect();

  // 编写响应
  //let resp = "HTTP/1.1 200 OK\r\n\r\n";
  //stream.write_all(resp.as_bytes()).unwrap();

  // 返回html
  let status_line = "HTTP/1.1 200 OK";
  let contents = fs::read_to_string("basic/src/hello.html").unwrap();
  let length = contents.len();
  let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
  stream.write_all(response.as_bytes()).unwrap();
}

// 验证请求并有选择的进行响应
fn handle_connection1(mut stream: TcpStream) {
  let buf_reader = BufReader::new(&mut stream);
  //let req_line = buf_reader.lines().next().unwrap().unwrap_or(String::new());
  let req_line = buf_reader.lines().next().unwrap_or(Ok(String::new())).unwrap_or(String::new());

  let status_line = "HTTP/1.1 200 OK";
  let mut contents = String::from("hello rust");
  if req_line == "GET / HTTP/1.1" {
    contents = fs::read_to_string("basic/src/hello.html").unwrap();
  } else {
  }
    let length = contents.len();
    let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
    stream.write_all(response.as_bytes()).unwrap();
}
